const { app, BrowserWindow, ipcMain, Menu, Notification } = require('electron');
const path = require('path');
const Store = require('electron-store');
const crypto = require('crypto');
const os = require('os');

const store = new Store();

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    minWidth: 1200,
    minHeight: 800,
    // maxWidth: 1200,
    // maxHeight: 800,
    webPreferences: {
      nodeIntegration: true,        // 安全风险
      contextIsolation: false       // 安全风险
    },
    titleBarStyle: 'hidden',
    frame: false,
    show: false
  });

  mainWindow.loadFile('index.html');

  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });

  // 开发环境下打开开发者工具
  if (process.argv.includes('--dev')) {
    mainWindow.webContents.openDevTools();
  }

  // 添加窗口关闭前的处理
  mainWindow.on('close', (event) => {
    if (process.platform === 'darwin') {
      // macOS: 阻止默认关闭，改为隐藏
      event.preventDefault();
      mainWindow.hide();
    } else {
      // Windows/Linux: 正常关闭
      if (mainWindow && !mainWindow.isDestroyed() && mainWindow.webContents) {
        mainWindow.webContents.send('app-will-close');
      }
    }
  });

  // IPC 事件处理
  ipcMain.on('window-close', () => {
    if (process.platform === 'darwin') {
      // macOS: 隐藏窗口
      if (mainWindow && !mainWindow.isDestroyed()) {
        mainWindow.hide();
      }
    } else {
      // Windows/Linux: 退出应用
      app.quit();
    }
  });

  // 应用激活事件（macOS 特有）
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    } else if (mainWindow) {
      // 显示已存在的窗口
      mainWindow.show();
    }
  });

  // 窗口全部关闭事件
  app.on('window-all-closed', () => {
    // macOS 上保持应用运行
    if (process.platform !== 'darwin') {
      app.quit();
    }
  });

  // 添加窗口失去焦点事件（后台运行）
  mainWindow.on('blur', () => {
    mainWindow.webContents.send('app-blur');
  });

  // 添加窗口获得焦点事件（前台运行）
  mainWindow.on('focus', () => {
    mainWindow.webContents.send('app-focus');
  });
}

// IPC 事件处理
ipcMain.handle('get-settings', () => {
  return store.get('settings', {
    pomodoroTime: 25,
    shortBreak: 5,
    longBreak: 15
  });
});

ipcMain.handle('save-settings', (event, settings) => {
  store.set('settings', settings);
  return true;
});

// 新增：处理白噪音清理完成的信号
ipcMain.on('white-noise-cleanup-complete', () => {
  // 白噪音清理完成后，真正关闭应用
  app.quit();
});

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// 新增：应用即将退出时的处理
app.on('before-quit', (event) => {
  if (mainWindow && !mainWindow.isDestroyed()) {
    event.preventDefault();
    // 通知渲染进程清理白噪音
    mainWindow.webContents.send('app-before-quit');
  }
});

// 设置应用菜单
Menu.setApplicationMenu(null);

// 窗口控制事件
ipcMain.on('window-minimize', () => {
  mainWindow.minimize();
});

ipcMain.on('window-maximize', () => {
  if (mainWindow.isMaximized()) {
    mainWindow.unmaximize();
  } else {
    mainWindow.maximize();
  }
});

ipcMain.on('window-close', () => {
  // 检查窗口是否仍然存在且未被销毁
  if (mainWindow && !mainWindow.isDestroyed()) {
    // 发送清理信号给渲染进程
    mainWindow.webContents.send('app-will-close');

    // 立即关闭窗口
    mainWindow.close();
  }

  // 设置超时，确保应用能够退出
  setTimeout(() => {
    if (!app.isQuiting) {
      app.quit();
    }
  }, 1000);
});

// 处理通知请求
ipcMain.on('show-notification', (event, { title, body }) => {
  if (Notification.isSupported()) {
    const notification = new Notification({
      title: title,
      body: body,
      icon: path.join(__dirname, 'build/icon.png')
    });

    notification.show();
  }
});


// 生成基于机器的唯一密钥
function getMachineKey() {
  const machineId = os.hostname() + os.platform() + os.arch();
  return crypto.createHash('sha256').update(machineId).digest('hex').substring(0, 32);
}

// 加密数据
function encryptData(data) {
  const key = getMachineKey();
  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipher('aes-256-cbc', key);
  let encrypted = cipher.update(JSON.stringify(data), 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return iv.toString('hex') + ':' + encrypted;
}

// 解密数据
function decryptData(encryptedData) {
  try {
    const key = getMachineKey();
    const parts = encryptedData.split(':');
    const iv = Buffer.from(parts[0], 'hex');
    const encrypted = parts[1];
    const decipher = crypto.createDecipher('aes-256-cbc', key);
    let decrypted = decipher.update(encrypted, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return JSON.parse(decrypted);
  } catch (error) {
    return null; // 解密失败，返回空数据
  }
}

// 修改IPC处理函数
ipcMain.handle('get-todos', () => {
  const encryptedData = store.get('todos_encrypted', null);
  if (encryptedData) {
    const decryptedData = decryptData(encryptedData);
    return decryptedData || [];
  }
  return [];
});

ipcMain.handle('save-todos', (event, todos) => {
  const encryptedData = encryptData(todos);
  store.set('todos_encrypted', encryptedData);
  // 清除旧的明文数据
  store.delete('todos');
  return true;
});


// 在应用启动时检查并清理测试数据
app.whenReady().then(() => {
  // 如果是生产环境，清理可能的测试数据
  if (!process.argv.includes('--dev')) {
    cleanTestData();
  }
  createWindow();
});

function cleanTestData() {
  // 检查是否存在测试数据标识
  const isTestData = store.get('__test_data__', false);
  if (isTestData) {
    // 清理所有数据
    store.clear();
    console.log('Test data cleaned on production startup');
  }
}


// 基于用户登录信息创建独立存储
function createUserStore(userId) {
  return new Store({
    name: `user-${crypto.createHash('md5').update(userId).digest('hex')}`
  });
}

// 在用户登录后切换到用户专属存储
ipcMain.handle('user-login', (event, userInfo) => {
  const userStore = createUserStore(userInfo.id);
  // 将当前store替换为用户专属store
  store = userStore;
  return true;
});


// 添加数据校验和
function addChecksum(data) {
  const checksum = crypto.createHash('md5').update(JSON.stringify(data)).digest('hex');
  return { data, checksum };
}

function verifyChecksum(dataWithChecksum) {
  if (!dataWithChecksum || !dataWithChecksum.data || !dataWithChecksum.checksum) {
    return false;
  }
  const expectedChecksum = crypto.createHash('md5').update(JSON.stringify(dataWithChecksum.data)).digest('hex');
  return expectedChecksum === dataWithChecksum.checksum;
}


// 添加认证相关的 IPC 处理
ipcMain.handle('get-auth-token', () => {
  return store.get('authToken', null);
});

ipcMain.handle('get-token-type', () => {
  return store.get('tokenType', 'Bearer');
});

ipcMain.handle('get-current-user', () => {
  return store.get('currentUser', null);
});

ipcMain.handle('save-auth-token', (event, token) => {
  store.set('authToken', token);
  return true;
});

ipcMain.handle('save-token-type', (event, tokenType) => {
  store.set('tokenType', tokenType);
  return true;
});

ipcMain.handle('save-current-user', (event, user) => {
  store.set('currentUser', user);
  return true;
});

ipcMain.handle('clear-auth-data', () => {
  store.delete('authToken');
  store.delete('tokenType');
  store.delete('currentUser');
  return true;
});